﻿package fj.utils
{
	import flash.display.Stage;

	import fj.utils.FJHistoryItem;

	public class FJHistory
	{
		public var length:uint = 50;

		private var historyStack:Array = new Array();
		private var index:int = -1;
		private var undoMode:Boolean = false;

		public function get canUndo ():Boolean
		{
			return index >= 0;
		}
		public function get canRedo ():Boolean
		{
			return index < historyStack.length - 1;
		}
		public function undo ():FJHistoryItem
		{
			if ( canUndo ) {
				undoMode = true;
				return historyStack[index--];
			}
			return null;
		}
		public function redo ():FJHistoryItem
		{
			if ( canRedo ) {
				if ( !undoMode ) {
					return historyStack[++index];
				}
			}
			return null;
		}
		public function record ( action:String, params:Array ):void
		{
			historyStack.splice ( index+1, historyStack.length-(index+1) );
			historyStack.push ( new FJHistoryItem( action, params ) );
			if ( historyStack.length > length ) {
				historyStack.splice ( 0, 1 );
			}
			index = historyStack.length - 1;
		}
		public function redoaction ( action:String, params:Array ):void
		{
			var item:FJHistoryItem;
			if ( undoMode ) {
				item = historyStack[index + 1];
				if ( item != null ) {
					item.redoAction = action;
					item.redoParameters = params;
				}
				undoMode = false;
			}
		}
	}
}